package org.example.lotterysystem.dao.handler;

import org.example.lotterysystem.common.errorcode.GlobalErrorCode;
import org.example.lotterysystem.common.exception.ControllerException;
import org.example.lotterysystem.common.exception.ServiceException;
import org.example.lotterysystem.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice //可以捕获全局抛的异常
public class GlobalExceptionHander {
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHander.class);

    @ExceptionHandler(value = ControllerException.class)
    public CommonResult<?> controllerException(final ControllerException e) {
        //打印错误日志
        logger.error("controllerException", e);
        //构造错误结果
        return CommonResult.error(
                GlobalErrorCode.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }


    @ExceptionHandler(value = ServiceException.class)
    public CommonResult<?> serviceException(final ServiceException e) {
        //打印错误日志
        logger.error("serviceException", e);
        //构造错误结果
        return CommonResult.error(
                GlobalErrorCode.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }


    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> exception(final Exception e) {
        //打印错误日志
        logger.error("服务异常", e);
        //构造错误结果
        return CommonResult.error(
                GlobalErrorCode.INTERNAL_SERVER_ERROR.getCode(),
                e.getMessage());
    }
}
